package libs

import (
	"fmt"
	"image"
	"image/png"
	"io"
	"mime/multipart"
	"os"
	"path/filepath"
	"time"
)

type AppUploadHelper struct {
}

func NewAppUploadHelper() *AppUploadHelper {

	helper := &AppUploadHelper{
		// AppId:   appid,
		// VerName: version,
	}

	return helper
}

// 创建临时保存目录
func (c *AppUploadHelper) CreateTempFolder() (string, error) {
	now := time.Now()
	var path = filepath.Join("temp", fmt.Sprintf("%d-%d", now.Year(), now.Month()))

	if _, err := os.Stat(path); os.IsNotExist(err) {
		err = os.MkdirAll(path, os.ModePerm)
		if err != nil {
			return "", err
		}
	}

	return path, nil
	// dest := filepath.Join(uploads, fileHeader.Filename)
}

func (c *AppUploadHelper) SavaAs(file multipart.File, filename string) error {

	tempPath, _ := c.CreateTempFolder()

	dest := filepath.Join(tempPath, filename)
	destFile, _ := os.Create(dest)
	defer destFile.Close()

	_, err := io.Copy(destFile, file)

	if err == nil {
		go readIPA(dest)
	}

	return err
}

func readIPA(dest string) error {
	app, err := NewAppParser(dest)
	if err != nil {
		return err
	}

	host, _ := NewHostInfo()

	// 生成应用相关的文件
	// 1）生成图标文件，在下载时可以看
	appFolder := fmt.Sprintf("./static/%s/%s", app.BundleId, app.Version)
	createFolder(appFolder)

	iconpath := filepath.Join(appFolder, "icon.png")
	saveAppIcon(iconpath, app.Icon)

	// 2）iOS生成对应的 plist 文件
	plistDestPath := filepath.Join(appFolder, "info.plist")
	NewPlist(host, app, plistDestPath)

	// 3) 拷贝ipa文件到相关版本目录
	iosipa := filepath.Join(appFolder, "ios.ipa")
	iosFile, _ := os.Create(iosipa)

	source, err := os.Open(dest)
	if err != nil {
		return err
	}
	defer source.Close()

	_, err = io.Copy(iosFile, source)
	defer iosFile.Close()

	return err
}

func createFolder(folderPath string) {
	if _, err := os.Stat(folderPath); os.IsNotExist(err) {
		err = os.MkdirAll(folderPath, os.ModePerm)
		if err != nil {
			fmt.Println("create folder error:", err)
		}
		err = os.Chmod(folderPath, os.ModePerm)
		if err != nil {
			fmt.Println("chmod folder error:", err)
		}
	}
}

func saveAppIcon(iconpath string, iconImage image.Image) {
	iconfile, err := os.Create(iconpath)
	if err != nil {
		fmt.Println(err)
	}
	defer iconfile.Close()
	png.Encode(iconfile, iconImage)
}
